# -*- coding: utf-8 -*-
"""
    .filename
    ~~~~~~~~~~~~~~

    Description

    :create by: lyncir
    :date: 2020-06-23 17:04:46 (+0800)
    :last modified date: 2020-07-24 16:08:15 (+0800)
    :last modified by: lyncir
"""
from pyshare.core.context import action_context_storage
from pyshare.framework.dal.models import TranslatedField
from pyshare.const.lang_enum import LangMapping
from common.service_config import get_app_id
from pyshare.dal.gameconfig.game_env import get_config_env_set
from pyshare.dal.gameconfig.query import getProfile


def get_instance_as_translated(instance, language_code=None):
    """
    对实例进行翻译

    首先先找到需要翻译的字段`TranslatedField`，然后从翻译表`TcLanguageTranslate`
    拿取翻译，最后替换上已翻译的数据

    :param Adapter instance: 适配器实例
    :param str language_code: 语言代码
    :return:
    """
    if instance is None:
        return instance

    # 从上下文中获取语言代码
    if language_code is None:
        ctx = action_context_storage.ctx
        if hasattr(ctx, 'lang'):
            language_code = action_context_storage.ctx.lang

    # 从配置中取默认的
    if language_code is None:
        language_code = get_config_env_set('Languages').get(get_app_id(), None)

    # 设置默认的
    if language_code is None:
        language_code = 'zh-cn'

    language = LangMapping.mapping.get(language_code)

    # 获取
    fields = instance.model_class._meta.fields
    for field_name, field in fields.iteritems():
        # 字段值
        value = getattr(instance, field_name, None)

        if value is not None:
            value_type = type(field)

            # Case 1: 如果是翻译字段，则从表中获取
            if value_type == TranslatedField:
                record = getProfile("TcLanguageTranslate", LangKey=value)
                new_value = getattr(record, language)

            # Case 2: 取原值
            else:
                new_value = value

            setattr(instance, field_name, new_value)

    return instance


def get_all_instances_as_translated(instances, language_code=None):
    """
    对所有实例进行翻译, 可迭代

    :param Model instances: 多model实例
    :param str language_code: 语言代码
    :return:
    """
    if not instances:
        return instances

    # 从上下文中获取语言代码
    if language_code is None:
        ctx = action_context_storage.ctx
        if hasattr(ctx, 'lang'):
            language_code = action_context_storage.ctx.lang

    # 从配置中取默认的
    if language_code is None:
        language_code = get_config_env_set('Languages').get(get_app_id(), None)

    # 设置默认的
    if language_code is None:
        language_code = 'zh-cn'

    results = []
    for instance in instances:
        result = get_instance_as_translated(instance, language_code=language_code)
        results.append(result)

    return results
